package com.xly.webclick.base;

import android.databinding.DataBindingUtil;
import android.databinding.OnRebindCallback;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

/**
 * Created by xuleyuan on 2018/8/15
 */

public abstract class BaseActivity<V extends ViewDataBinding, VM extends BaseViewModel> extends AppCompatActivity {

    VM viewModel;
    public V binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initViewDataBinding();
        viewModel.onCreate(savedInstanceState);
    }

    private void initViewDataBinding() {
        viewModel = initViewModel();
        binding = DataBindingUtil.setContentView(this, initContentView());
        binding.addOnRebindCallback(new OnRebindCallback() {
            @Override
            public void onBound(ViewDataBinding binding) {
                super.onBound(binding);
                onViewBindingComplete();
            }
        });
        initBindingView(binding);
        binding.setVariable(initVariableId(), viewModel);
    }

    private void onViewBindingComplete() {

    }

    protected abstract int initVariableId();

    private void initBindingView(V binding) {

    }

    protected abstract int initContentView();



    @Override
    protected void onResume() {
        super.onResume();
        viewModel.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        viewModel.onDestroy();
    }

    @Override
    protected void onStop() {
        super.onStop();
        viewModel.onStop();
    }

    @Override
    protected void onPause() {
        super.onPause();
        viewModel.onPause();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        viewModel.onWindowFocusChanged(hasFocus);
    }

    public abstract VM initViewModel();

}
